package com.enqualcomm.kids.activities;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.base.MyHandler;
import com.enqualcomm.kids.config.StateCode;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.mvp.register.RegisterPagerAdapter;
import com.enqualcomm.kids.mvp.register.RegisterStep1Pager;
import com.enqualcomm.kids.mvp.register.RegisterStep2Pager;
import com.enqualcomm.kids.mvp.register.RegisterStep3Pager;
import com.enqualcomm.kids.mvp.register.RegisterStep4Pager;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.GetValidCodeParams;
import com.enqualcomm.kids.network.socket.request.LoginParams;
import com.enqualcomm.kids.network.socket.request.RegisterParams;
import com.enqualcomm.kids.network.socket.request.TerminalListParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.LoginResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.BasePager;
import com.enqualcomm.kids.view.MyViewPager2;

import java.util.ArrayList;
import java.util.List;

import common.utils.DensityUtil;
import common.utils.PromptUtil;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {


    private View root_view;
    public static String ADD_ACT;
    public static String MAIN_ACT;
    private MyViewPager2 mViewPager;
    private TextView title_bar_name;
    private RegisterParams registerParams;
    private RegisterPagerAdapter adapter;
    /**
     * 有些页面得联网完成才跳转，需要防止多次点击,-1表示没有正在加载的页面
     *
     * 点击注册时，需要联网3次，loadingPage == -1 还没有注册， -2 注册成功没有登录， -3 登陆成功没有获取设备列表
     */
    private int loadingPage;
    private List<BasePager> pages;
    NetworkModel networkModel;
    public static final int START_COUNT = 1;
    int lasttime;
    boolean isShowSoftInput;


    MyHandler validcodeHandler = new MyHandler(this);

    @Override
    protected void handleMessage(Message msg) {
        switch (msg.what) {
            case START_COUNT:
                if (--lasttime >= 0) {
                    ((RegisterStep2Pager) pages.get(1)).refreshLasttime(lasttime);
                    validcodeHandler.sendEmptyMessageDelayed(START_COUNT, 1000);
                } else {
                    lasttime = 120;
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        networkModel = new NetworkModel();
        initView();
        loadingPage = -1;
        lasttime = 120;
        MAIN_ACT = getString(R.string.open_app_prefix)+getString(R.string.app_name);
        ADD_ACT= getString(R.string.add_watch);
    }

    private void initView() {
        //初始化title
        findViewById(R.id.title_bar_left_iv).setOnClickListener(this);
//        title_bar_name = (TextView) findViewById(R.id.title_bar_title_tv);
        title_bar_name = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
        View title_bar_terminal_icon_iv = findViewById(R.id.title_bar_terminal_icon_iv);
        title_bar_terminal_icon_iv.setVisibility(View.GONE);
        title_bar_name.setVisibility(View.VISIBLE);
        title_bar_name.setText(getString(R.string.new_user));

        mViewPager = (MyViewPager2) findViewById(R.id.pager);
        pages = new ArrayList<>();
        pages.add(new RegisterStep1Pager(this));
        adapter = new RegisterPagerAdapter(pages);
        mViewPager.setAdapter(adapter);

//        root_view = findViewById(R.id.root);
//        root_view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                int heightDiff = root_view.getRootView().getHeight() - root_view.getHeight();
//                if (heightDiff > 100) { // 如果高度差超过100像素，就很有可能是有软键盘...
//                    if (isShowSoftInput) {
//                        return;
//                    }
//                    root_view.setPadding(0, 0, 0, 0);
//
//                    isShowSoftInput = true;
//                } else {
//                    if (!isShowSoftInput) {
//                        return;
//                    }
//                    root_view.setPadding(0, 0, 0, DensityUtil.dip2px(RegisterActivity.this, 20));
//
//                    isShowSoftInput = false;
//                }
//            }
//        });
    }


    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        validcodeHandler.removeMessages(START_COUNT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_left_iv:
                int currentPage = mViewPager.getCurrentItem();
                if (currentPage==0) {
                    finish();
                }else if (currentPage==3) {
                    // 如果注册完成，点回退需要到登陆界面，并输入账号密码
                    Intent data = new Intent();
                    data.putExtra("username", registerParams.getUsername());
                    data.putExtra("password", registerParams.getUserpwd());
                    data.putExtra("countryName",countryName);
                    data.putExtra("countryCode",countryCode);
                    setResult(2, data);
                    finish();
                }else {
                    if (loadingPage!=-1) {
                        return;//还在处理下一步点击事件中，不让点击后退，避免发生异常
                    }

                    //清除页面的数据
                    validcodeHandler.removeMessages(START_COUNT);
                    lasttime = 120;
                    for (int i = 0; i < pages.size(); i++) {
                        pages.get(i).clear();
                    }

                    //后退回第一步
                    mViewPager.setCurrentItem(0);
                    title_bar_name.setText(getString(R.string.new_user));
                }
                break;
            default:
                break;
        }
    }

    public void nextPage(int nextPage,String inputStr){
        if (loadingPage == nextPage) {
            return;
        }
        switch (nextPage) {
            case 1://账号输入完成，开始输入验证码
                String[] split = inputStr.split(":");

                registerParams = new RegisterParams();
                registerParams.setUsername(split[0]);
                registerParams.setCountry(split[1]);
//                registerParams.setUsername(inputStr);
                //应该确定发送验证码完成之后，再跳转
                loadingPage = 1;
                networkModel.loadDataFromServer(new SocketRequest<BasicResult>(new GetValidCodeParams(split[0],split[1]), new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        loadingPage = -1;
                        PromptUtil.toast(getApplicationContext(),R.string.app_no_connection);
                        ((RegisterStep1Pager) pages.get(0)).setBtnEnable(true);
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        loadingPage = -1;
                        if (response.code == 0){
                            if (pages.size()<2) {
                                pages.add(new RegisterStep2Pager(RegisterActivity.this));
                                adapter.notifyDataSetChanged();
                            }
                            ((RegisterStep2Pager) pages.get(1)).setUsername(registerParams.getUsername());

                            mViewPager.setCurrentItem(1);
                            title_bar_name.setText(getString(R.string.input_validcode));

                            //定时刷新
                            validcodeHandler.sendEmptyMessage(START_COUNT);
                        }else if (response.code==2){
                            ((RegisterStep1Pager) pages.get(0)).resetView();
                            PromptUtil.toast(getApplicationContext(),R.string.username_exists);
                        }

                    }
                }));
                break;
            case 2://验证码输入完成，开始输入密码
                validcodeHandler.removeMessages(START_COUNT);
                registerParams.setValidcode(inputStr);
                if (pages.size()<3) {
                    pages.add(new RegisterStep3Pager(this));
                    adapter.notifyDataSetChanged();
                }

                mViewPager.setCurrentItem(2);
                title_bar_name.setText(getString(R.string.register));
                break;
            case 3://密码输入完成，发送注册请求
                if (loadingPage == -1) {
                    registerParams.setUserpwd(inputStr);
                    loadingPage = 3;
                    networkModel.loadDataFromServer(new SocketRequest<BasicResult>(registerParams, new NetworkListener<BasicResult>() {
                        @Override
                        public void onError(VolleyError error) {
                            loadingPage = -1;
                            PromptUtil.toast(getApplicationContext(),R.string.app_no_connection);
                            ((RegisterStep3Pager) pages.get(2)).setBtnEnable(true);
                        }

                        @Override
                        public void onSuccess(BasicResult response) {
                            if (response.code==0){
                                //注册成功
                                login(registerParams.getUsername(), registerParams.getUserpwd(),registerParams.getCountry());
                            }else if (response.code==6){
                                loadingPage = -1;
                                PromptUtil.toast(getApplicationContext(),R.string.validcode_wrong);
                            }
                        }
                    }));
                }else if (loadingPage == -2) {
                    // 直接登陆?
                    loadingPage = 3;
                    login(registerParams.getUsername(), registerParams.getUserpwd(),registerParams.getCountry());
                }else if (loadingPage == -3) {
                    loadingPage = 3;
                    AppDefault appDefault = new AppDefault();
                    terminallist(appDefault.getUserkey(),appDefault.getUserid());
                }
                break;
            case 4:
                //设置完成
                if (ADD_ACT.equals(inputStr)) {
                    // 添加设备
                    setResult(200);
                    finish();
                }else {
                    //直接进入在哪儿
                    setResult(100);
                    finish();
                }
                break;
        }
    }

    private String countryCode;
    private String countryName;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==10000&&resultCode ==10001){
            countryCode = data.getStringExtra("number");
            countryName = data.getStringExtra("name");
            ((RegisterStep1Pager)pages.get(0)).onCountryChooded(countryName,countryCode);
        }
    }


    /**
     * 重新获取验证码
     */
    public void getValidCodeAgain() {
        networkModel.loadDataFromServer(new SocketRequest<BasicResult>(new GetValidCodeParams(registerParams.getUsername(),registerParams.getCountry()),
                new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        validcodeHandler.sendEmptyMessage(START_COUNT);
                    }
                }));
    }

    private void login(final String username, final String password,final String country) {
        networkModel.loadDataFromServer(new SocketRequest<LoginResult>(new LoginParams(username, password,country),
                new NetworkListener<LoginResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        loadingPage = -2;
                        PromptUtil.toast(getApplicationContext(), R.string.app_no_connection);
                        ((RegisterStep3Pager) pages.get(2)).setBtnEnable(true);
                    }

                    @Override
                    public void onSuccess(LoginResult response) {
                        if (response.code == StateCode.OK) {
                            AppDefault appDefault = new AppDefault();
                            appDefault.setUserid(response.result.userid);
                            appDefault.setUserkey(response.result.userkey);
                            appDefault.setProducts(response.result.products);

                            appDefault.setUsername(username);
                            appDefault.setPassword(password);
                            appDefault.setCountry(country);

                            terminallist(response.result.userkey,response.result.userid);
                        }
                    }
                }));
    }


    private void terminallist(String userkey,String userid){
        networkModel.loadDataFromServer(new SocketRequest<TerminallistResult>(new TerminalListParams(userkey, userid), new NetworkListener<TerminallistResult>() {
            @Override
            public void onError(VolleyError error) {
                loadingPage = -3;
                ((RegisterStep3Pager) pages.get(2)).setBtnEnable(true);
            }

            @Override
            public void onSuccess(TerminallistResult response) {
                if (response.code==0){
                    RegisterStep4Pager registerStep4Pager = new RegisterStep4Pager(RegisterActivity.this);
                    if (response.result.isEmpty()) {//添加手表
                        registerStep4Pager.setData(ADD_ACT,
                                registerParams.getUsername(),
                                registerParams.getUserpwd());
                    }else {//进入在哪儿
                        registerStep4Pager.setData(MAIN_ACT,
                                registerParams.getUsername(),
                                registerParams.getUserpwd());
                    }

                    pages.add(registerStep4Pager);
                    adapter.notifyDataSetChanged();
                    mViewPager.setCurrentItem(3);
                    title_bar_name.setText(getString(R.string.regist_done));
                }
            }
        }));
    }
}
